package com.internetCafes.spms.common.module.mybatisPlus.plugin;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.internetCafes.spms.common.utils.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        if (metaObject.hasGetter("createTime")) {
            if (metaObject.getValue("createTime") == null) {
                this.setFieldValByName("createTime", new Date(), metaObject);
            }
        }
        if (metaObject.hasGetter("createBy")) {
            if (metaObject.getValue("createBy") == null && ShiroUtils.getUserEntity() != null) {
                this.setFieldValByName("createBy", ShiroUtils.getUserEntity().getId(), metaObject);
            }
        }
        if (metaObject.hasGetter("createByName")) {
            if (metaObject.getValue("createByName") == null && ShiroUtils.getUserEntity() != null) {
                this.setFieldValByName("createByName", ShiroUtils.getUserEntity().getNickName(), metaObject);
            }
        }
        if (metaObject.hasGetter("tenantId")) {
            if (metaObject.getValue("tenantId") == null && ShiroUtils.getUserEntity() != null) {
                this.setFieldValByName("tenantId", ShiroUtils.getUserEntity().getDeptId(), metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");

        this.setFieldValByName("updateBy", ShiroUtils.getUserEntity().getId(), metaObject);

        this.setFieldValByName("updateTime", new Date(), metaObject);
    }
}
